package com.lv.suyiyong.hfr.utils.login

import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.util.TypedValue
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ConvertUtils.dp2px
import com.blankj.utilcode.util.LogUtils
import com.lv.common.BuildConfig
import com.lv.suyiyong.hfr.moudel.MainViewModel
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.PreLoginResultListener
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.TokenRet
import com.nirvana.tools.core.ComponentSdkCore.getApplicationContext

/**
 * 作者： ygx
 * 创建日期：2023/2/16 3:20 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：Login 封装
 */
object LoginUtils {
    private var mCheckListener: TokenResultListener? = null
    private var mTokenResultListener: TokenResultListener? = null
    private var sdkAvailable = true
    private var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null

    /**
     * 先提醒用户要申请权限的目的(activity)
     */
    fun checkPhoneLogin(context: Context, loginUtilsCallback: LoginUtilsCallback) {
        val secretInfo = BuildConfig.AUTH_SECRET
        mCheckListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                try {
                    LogUtils.e("checkEnvAvailable：$s")
                    val pTokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS == pTokenRet.code) {
                        accelerateLoginPage(5000, loginUtilsCallback)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                sdkAvailable = false
                LogUtils.e("checkEnvAvailable：$s")
                //终端环境检查失败之后 跳转到其他号码校验方式
                //如果环境检查失败 使用其他登录方式

                //如果环境检查失败 使用其他登录方式
                mPhoneNumberAuthHelper!!.setAuthListener(null)
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(context, mCheckListener)
        mPhoneNumberAuthHelper?.reporter?.setLoggerEnable(true)
        mPhoneNumberAuthHelper?.setAuthSDKInfo(secretInfo)
        mPhoneNumberAuthHelper?.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
    }

    /**
     * 在不是一进app就需要登录的场景 建议调用此接口 加速拉起一键登录页面
     * 等到用户点击登录的时候 授权页可以秒拉
     * 预取号的成功与否不影响一键登录功能，所以不需要等待预取号的返回。
     * @param timeout
     */
    fun accelerateLoginPage(timeout: Int, callback: LoginUtilsCallback) {
        mPhoneNumberAuthHelper!!.accelerateLoginPage(timeout, object : PreLoginResultListener {
            override fun onTokenSuccess(s: String) {
                callback.loginCallback(true, "预取号成功: $s")
            }

            override fun onTokenFailed(s: String, s1: String) {
                callback.loginCallback(false, "预取号失败：$s1")
            }
        })
    }

    /**
     * 配置竖屏样式
     */
    fun configLoginTokenPort(context: Context) {
        mPhoneNumberAuthHelper!!.removeAuthRegisterXmlConfig()
        mPhoneNumberAuthHelper!!.removeAuthRegisterViewConfig()
        mPhoneNumberAuthHelper!!.addAuthRegistViewConfig(
            "switch_acc_tv",
            AuthRegisterViewConfig.Builder()
                .setView(initDynamicView(context))
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setCustomInterface { mPhoneNumberAuthHelper!!.quitLoginPage() }.build()
        )
        var authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
        if (Build.VERSION.SDK_INT == 26) {
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND
        }
        mPhoneNumberAuthHelper!!.setAuthUIConfig(
            AuthUIConfig.Builder()
                .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
                .setAppPrivacyColor(Color.GRAY, Color.parseColor("#002E00"))
                .setPrivacyState(false)
                .setCheckboxHidden(true)
                .setStatusBarColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                .setLightColor(true)
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .setProtocolShakePath("protocol_shake")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setLogoImgPath("ic_logo")
                .setScreenOrientation(authPageOrientation)
                .create()
        )
    }

    private fun initDynamicView(context: Context): View? {
        val switchTV = TextView(context)
        val mLayoutParams2 =
            RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, dp2px(50.0f))
        mLayoutParams2.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
        mLayoutParams2.setMargins(0, dp2px(450.0f), 0, 0)
        switchTV.text = "-----  自定义view  -----"
        switchTV.setTextColor(-0x666667)
        switchTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13.0f)
        switchTV.layoutParams = mLayoutParams2
        return switchTV
    }

    /**
     * 拉起授权页
     * @param timeout 超时时间
     */
    fun getLoginToken(
        timeout: Int,
        viewModel: MainViewModel,
        lifecycleOwner: LifecycleOwner,
        activity: Activity
    ) {
        val mUIConfig = FullPortConfig(activity, viewModel, lifecycleOwner, mPhoneNumberAuthHelper)
        mUIConfig.configAuthPage()
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
//                hideLoadingDialog()
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                        LogUtils.e("唤起授权页成功：$s")
                    }
                    if (ResultCode.CODE_SUCCESS == tokenRet.code) {
                        LogUtils.e("获取token成功：$s")
                        val token = tokenRet.token

                        //模拟网络请求
                        LogUtils.i("一键登录换号：token: $token")
                        /**
                         * 开发者自己app的服务端对接阿里号码认证，并提供接口给app调用
                         * 1、调用app服务端接口将一键登录token发送过去
                         * 2、app服务端拿到token调用阿里号码认证服务端换号接口，获取手机号
                         * 3、app服务端拿到手机号帮用户完成注册以及登录的逻辑，返回账户信息给app
                         * @return 账户信息
                         */
//                        getResultWithToken(token)
                        mPhoneNumberAuthHelper!!.setAuthListener(null)
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                LogUtils.e("获取token失败：$s")
//                hideLoadingDialog()
                mPhoneNumberAuthHelper!!.hideLoginLoading()
                //如果环境检查失败 使用其他登录方式
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_USER_CANCEL != tokenRet?.getCode()) {
                        Toast.makeText(
                            getApplicationContext(),
                            "一键登录失败切换到其他登录方式",
                            Toast.LENGTH_SHORT
                        ).show()
//                        val pIntent: Intent = Intent(
//                            this@OneKeyLoginDelayActivity,
//                            MessageActivity::class.java
//                        )
//                        startActivityForResult(pIntent, 1002)
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                mPhoneNumberAuthHelper!!.quitLoginPage()
                mPhoneNumberAuthHelper!!.setAuthListener(null)
            }
        }
        mPhoneNumberAuthHelper!!.setAuthListener(mTokenResultListener)
        mPhoneNumberAuthHelper!!.getLoginToken(activity, timeout)
        LogUtils.e("正在唤起授权页")
//        showLoadingDialog("正在唤起授权页")
    }
}

interface LoginUtilsCallback {

    fun loginCallback(
        loginByAli: Boolean,
        data: String
    )

}
